package pers.corvey.studyjava.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import pers.corvey.studyjava.dao.CourseDAO;
import pers.corvey.studyjava.dao.ExampleDAO;
import pers.corvey.studyjava.dao.TestDAO;
import pers.corvey.studyjava.model.Course;
import pers.corvey.studyjava.model.Example;
import pers.corvey.studyjava.model.Test;
import pers.corvey.studyjava.model.json.SearchResultJson;

@Service
public class SearchService {

    @Autowired
    private CourseDAO courseDAO;
    
    @Autowired
    private TestDAO testDAO;
    
    @Autowired
    private ExampleDAO exmapleDao;
    
    public List<SearchResultJson> search(String keyword) {
        List<SearchResultJson> ret = new ArrayList<>();
        keyword += "%";
        ret.addAll(searchCourse(keyword));
        ret.addAll(searchTest(keyword));
        ret.addAll(searchExample(keyword));
        System.out.println(ret);
        return ret;
    }
    
    private List<SearchResultJson> searchCourse(String keyword) {
        List<SearchResultJson> ret = new ArrayList<>();
        Iterable<Course> courses = courseDAO.findByTitleLike(keyword);
        for (Course course : courses) {
            SearchResultJson result = new SearchResultJson();
            result.setTypeName("课程知识");
            result.setTitle(course.getTitle());
            result.setDescription(course.getDescription());
            result.setUrl("/courseCategorys/" + course.getCategoryId() + "/courses/" + course.getId());
            ret.add(result);
            System.out.println(result);
        }
        return ret;
    }
    
    private List<SearchResultJson> searchTest(String keyword) {
        List<SearchResultJson> ret = new ArrayList<>();
        Iterable<Test> tests = testDAO.findByTitleLike(keyword);
        for (Test test : tests) {
            SearchResultJson result = new SearchResultJson();
            result.setTypeName("在线测试");
            result.setTitle(test.getTitle());
            result.setDescription(test.getDescription());
            result.setUrl("/tests/" + test.getId());
            ret.add(result);
            System.out.println(result);
        }
        return ret;
    }
    
    private List<SearchResultJson> searchExample(String keyword) {
        List<SearchResultJson> ret = new ArrayList<>();
        Iterable<Example> examples = exmapleDao.findByTitleLike(keyword);
        for (Example example : examples) {
            SearchResultJson result = new SearchResultJson();
            result.setTypeName("实例教程");
            result.setTitle(example.getTitle());
            result.setDescription(example.getDescription());
            result.setUrl("/examples/" + example.getId());
            ret.add(result);
            System.out.println(result);
        }
        return ret;
    }
}
